import requests
import json
import time
from typing import Tuple

class LLMService:
    def __init__(self):
        self.api_configs = {
            "qwen": {
                "url": "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation",
                "api_key": "sk-46fec8c5c579498685177f824631752f"
            },
            "chatglm": {
                "url": "https://open.bigmodel.cn/api/paas/v4/chat/completions",
                "api_key": "c0f46d383c1a435e9693df6889b18361.2lwAd22csH1wQbAJ"
            }
        }
    
    def call_qwen_api(self, prompt: str, model_name: str = "qwen-max", max_retries: int = 3) -> Tuple[str, float]:
        """调用阿里百炼Qwen API"""
        headers = {
            "Authorization": f"Bearer {self.api_configs['qwen']['api_key']}",
            "Content-Type": "application/json"
        }
        
        data = {
            "model": model_name,
            "input": {
                "messages": [
                    {
                        "role": "user",
                        "content": prompt
                    }
                ]
            },
            "parameters": {
                "result_format": "message"
            }
        }
        
        for attempt in range(max_retries):
            try:
                start_time = time.time()
                response = requests.post(
                    self.api_configs['qwen']['url'],
                    headers=headers,
                    json=data,
                    timeout=30
                )
                response_time = time.time() - start_time
                
                response.raise_for_status()
                result = response.json()
                return result['output']['choices'][0]['message']['content'], response_time
                
            except Exception as e:
                print(f"Qwen API第{attempt+1}次调用错误: {e}")
                if attempt < max_retries - 1:
                    time.sleep(2)
                else:
                    return f"抱歉，咨询服务暂时不可用，请稍后重试。错误信息: {str(e)}", 0
        
        return "抱歉，咨询服务暂时不可用，请稍后重试。", 0
    
    def call_chatglm_api(self, prompt: str, model_name: str = "glm-4", max_retries: int = 3) -> Tuple[str, float]:
        """调用智谱ChatGLM API"""
        headers = {
            "Authorization": f"Bearer {self.api_configs['chatglm']['api_key']}",
            "Content-Type": "application/json"
        }
        
        data = {
            "model": model_name,
            "messages": [
                {
                    "role": "user",
                    "content": prompt
                }
            ],
            "temperature": 0.7
        }
        
        for attempt in range(max_retries):
            try:
                start_time = time.time()
                response = requests.post(
                    self.api_configs['chatglm']['url'],
                    headers=headers,
                    json=data,
                    timeout=30
                )
                response_time = time.time() - start_time
                
                response.raise_for_status()
                result = response.json()
                return result['choices'][0]['message']['content'], response_time
                
            except Exception as e:
                print(f"ChatGLM API第{attempt+1}次调用错误: {e}")
                if attempt < max_retries - 1:
                    time.sleep(2)
                else:
                    return f"抱歉，咨询服务暂时不可用，请稍后重试。错误信息: {str(e)}", 0
        
        return "抱歉，咨询服务暂时不可用，请稍后重试。", 0
    
    def car_consultation(self, user_input: str) -> str:
        """汽车咨询服务"""
        prompt = f"""
        你是一个专业的汽车购车顾问，请根据用户的以下需求提供详细、专业的购车建议：
        
        {user_input}
        
        请按照以下结构提供建议：
        1. 推荐车型（3-5款）
        2. 每款车的优缺点分析
        3. 价格区间和性价比分析
        4. 使用场景匹配度
        5. 维护成本和保值率
        6. 最终推荐理由
        
        请用专业、易懂的语言回答，避免过于技术化的术语。
        """
        
        # 尝试调用Qwen，失败则调用ChatGLM
        try:
            response, response_time = self.call_qwen_api(prompt)
            if "抱歉" not in response:
                return response
        except:
            pass
        
        # 如果Qwen失败，尝试ChatGLM
        try:
            response, response_time = self.call_chatglm_api(prompt)
            return response
        except:
            return "非常抱歉，当前咨询服务暂时不可用，请您稍后重试。我们的技术团队正在尽快修复这个问题。"